const fs = require('fs');
const path = require('path');
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const config = require('../../config/default.json');

class StorageManager {
  constructor() {
    this.dataPath = path.resolve(config.storage.path);
    this.currentProject = config.storage.defaultProject;
    this.db = null;
    this.init();
  }

  init() {
    // 确保数据目录存在
    if (!fs.existsSync(this.dataPath)) {
      fs.mkdirSync(this.dataPath, { recursive: true });
    }

    // 确保默认项目文件存在
    const defaultProjectPath = path.join(this.dataPath, `${this.currentProject}.json`);
    if (!fs.existsSync(defaultProjectPath)) {
      const defaultData = {
        project: {
          name: "默认项目",
          description: "默认项目配置",
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        },
        utils: [],
        database: {
          tables: []
        },
        apis: [],
        workflows: []
      };
      fs.writeFileSync(defaultProjectPath, JSON.stringify(defaultData, null, 2));
    }

    // 初始化数据库连接
    this.loadProject(this.currentProject);
  }

  loadProject(projectName) {
    const projectPath = path.join(this.dataPath, `${projectName}.json`);
    if (!fs.existsSync(projectPath)) {
      throw new Error(`项目 ${projectName} 不存在`);
    }

    const adapter = new FileSync(projectPath);
    this.db = low(adapter);
    this.currentProject = projectName;
    return this.db.value();
  }

  getCurrentProject() {
    return this.currentProject;
  }

  getProjectList() {
    const files = fs.readdirSync(this.dataPath);
    return files
      .filter(file => file.endsWith('.json'))
      .map(file => file.replace('.json', ''));
  }

  createProject(name, description) {
    const projectPath = path.join(this.dataPath, `${name}.json`);
    if (fs.existsSync(projectPath)) {
      throw new Error(`项目 ${name} 已存在`);
    }

    const newProject = {
      project: {
        name,
        description,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      },
      utils: [],
      database: {
        tables: []
      },
      apis: [],
      workflows: []
    };

    fs.writeFileSync(projectPath, JSON.stringify(newProject, null, 2));
    return this.loadProject(name);
  }

  // 工具类相关操作
  getUtils() {
    return this.db.get('utils').value();
  }

  addUtil(util) {
    const utils = this.db.get('utils');
    const existingUtil = utils.find({ name: util.name }).value();
    
    if (existingUtil) {
      return utils
        .find({ name: util.name })
        .assign({ ...util, updatedAt: new Date().toISOString() })
        .write();
    } else {
      return utils
        .push({
          ...util,
          id: Date.now().toString(),
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        })
        .write();
    }
  }

  // 数据库表相关操作
  getTables() {
    return this.db.get('database.tables').value();
  }

  addTable(table) {
    const tables = this.db.get('database.tables');
    const existingTable = tables.find({ name: table.name }).value();
    
    if (existingTable) {
      return tables
        .find({ name: table.name })
        .assign({ ...table, updatedAt: new Date().toISOString() })
        .write();
    } else {
      return tables
        .push({
          ...table,
          id: Date.now().toString(),
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        })
        .write();
    }
  }

  // API接口相关操作
  getApis() {
    return this.db.get('apis').value();
  }

  addApi(api) {
    const apis = this.db.get('apis');
    const existingApi = apis.find({ path: api.path, method: api.method }).value();
    
    if (existingApi) {
      return apis
        .find({ path: api.path, method: api.method })
        .assign({ ...api, updatedAt: new Date().toISOString() })
        .write();
    } else {
      return apis
        .push({
          ...api,
          id: Date.now().toString(),
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        })
        .write();
    }
  }

  // 工作流相关操作
  getWorkflows() {
    return this.db.get('workflows').value();
  }

  addWorkflow(workflow) {
    const workflows = this.db.get('workflows');
    const existingWorkflow = workflows.find({ name: workflow.name }).value();
    
    if (existingWorkflow) {
      return workflows
        .find({ name: workflow.name })
        .assign({ ...workflow, updatedAt: new Date().toISOString() })
        .write();
    } else {
      return workflows
        .push({
          ...workflow,
          id: Date.now().toString(),
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        })
        .write();
    }
  }
}

// 单例模式
const storageManager = new StorageManager();
module.exports = storageManager; 